package com.shanyue.redwine.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.shanyue.redwine.activity.ActivityMain;
import com.shanyue.redwine.activity.ActivityWineCabinet;
import com.shanyue.redwine.http.rx.RxBus;
import com.shanyue.redwine.utils.Constants;
import com.shanyue.redwine.utils.LogUtils;

import java.util.Iterator;
import java.util.function.Consumer;

import cn.jpush.android.api.JPushInterface;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 项目：MeiYueHongJiu  包名：com.shanyue.redwine.receiver
 * <p>
 * huangxiaoyu
 * <p>
 * 2018/6/13
 * <p>
 * desc  极光广播接收器
 */
public class MyJPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";
    public static final String MESSAGE_RECEIVED_ACTION = "com.shanyue.redwine.receiver" + "" + "" + "" + "" + "" + ""
            + ".MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            LogUtils.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                LogUtils.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                LogUtils.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                processCustomMessage(context, bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                LogUtils.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                LogUtils.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
                String extrasStr = bundle.getString(JPushInterface.EXTRA_EXTRA);
                JSONObject jsonObject = JSONObject.parseObject(extrasStr);
                if (jsonObject.containsKey(Constants.JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE)) {
                    String type = jsonObject.getString(Constants.JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE);
                    if (ActivityWineCabinet.isForeground && type.equals(Constants
                            .JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE_WINECABINET_OPEN + "") || type.equals(Constants
                            .JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE_WINECABINET_CLOSE + "")) {
                        RxBus.getDefault().post(RxBus.RX_BUS_REFRESH_WINECABINET_LOG, true);
                    }
                }
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                LogUtils.d(TAG, "[MyReceiver] 用户点击打开了通知");
                String extrasStr = bundle.getString(JPushInterface.EXTRA_EXTRA);
                JSONObject jsonObject = JSONObject.parseObject(extrasStr);
                if (jsonObject.containsKey(Constants.JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE)) {
                    Intent startIntent = new Intent(context, ActivityMain.class);
                    startIntent.putExtra(Constants.JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE, jsonObject.getString
                            (Constants.JPUSH_CUSTOM_EXTRA_KEY_CONTENT_TYPE));
                    context.startActivity(startIntent);
                }
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                LogUtils.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface
                        .EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                LogUtils.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change " + "to" + " " +
                        connected);
            } else {
                LogUtils.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    LogUtils.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = JSON.parseObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keySet().iterator();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.get(myKey).toString() + "]");
                    }
                } catch (JSONException e) {
                    LogUtils.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (ActivityMain.isForeground) {
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent msgIntent = new Intent(MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra(KEY_MESSAGE, message);
            if (!TextUtils.isEmpty(extras)) {
                try {
                    JSONObject extraJson = JSON.parseObject(extras);
                    if (extraJson.keySet().size() > 0) {
                        msgIntent.putExtra(KEY_EXTRAS, extras);
                    }
                } catch (JSONException e) {

                }

            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
        }
    }
}
